package com.xidian.zhiancloud.service.workTicket;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xidian.zhiancloud.dao.syset.SysUserMapper;
import com.xidian.zhiancloud.dao.workTicket.HighFlowMapper;
import com.xidian.zhiancloud.model.syset.SysUser;
import com.xidian.zhiancloud.model.workTicket.HighFlow;
import com.xidian.zhiancloud.model.workTicket.HighTicket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@Service
public class HighFlowService extends ServiceImpl<HighFlowMapper, HighFlow> implements IService<HighFlow> {
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private HighFlowMapper highFlowMapper;

    @Autowired
    private HighFlowService highFlowService;

    /**
     * 返回当前大步骤下，所有子步骤的id
     *
     * @param companyId
     * @param currentStep
     * @return
     */
    public List<Long> getSubIdsByCurrent(Long companyId, Integer currentStep) {
        List<Long> subIdList = new LinkedList<>();
        // 根据companyId，在high_flow中获取记录
        LambdaQueryWrapper<HighFlow> query = Wrappers.<HighFlow>lambdaQuery();
        query.eq(HighFlow::getCompanyId, companyId);
        List<HighFlow> highFlows = highFlowMapper.selectList(query);
        // 根据currentStep判断当前大步骤下的所有小步骤，获取ids
        highFlows.forEach(subId -> {
            if (currentStep == subId.getBelongId()) {
                subIdList.add(subId.getId());
            }
        });
        return subIdList;
    }

    public List<Map<List<Long>, List<String>>> getEnableFieldMap(Long companyId, Integer currentStep, List<Long> subStepList) {
        // 返回值
        List<Map<List<Long>, List<String>>> operatorFieldList = new LinkedList<>();
        // 循环每一个小步骤，i是可操作列表的
        for (int i = 0; i < subStepList.size(); i++) {
            // 在t_user中获取操作人列表
            List<Long> operatorIds = getOperatorIdsList(subStepList.get(i), companyId);
            // 在high_flow中获得可编辑字段列表
            List<String> enableField = getEnableFieldList(subStepList.get(i));
            Map<List<Long>, List<String>> operatorFieldMap = new HashMap<List<Long>, List<String>>();
            operatorFieldMap.put(operatorIds, enableField);
            operatorFieldList.add(operatorFieldMap);
        }
        return operatorFieldList;
    }

    /**
     * 获取人员
     *
     * @param flowId
     * @param companyId
     * @return
     */
    private List<Long> getOperatorIdsList(Long flowId, Long companyId) {
        // 根据id在t_flow中查找小步骤的记录
        HighFlow highFlow = highFlowService.getById(flowId);
        // 大标准
        Integer selectStandard = highFlow.getSelectStandard();
        // 小标准
        String ids_s = highFlow.getSelectPerson();
        // 在t_user中进行人员筛选
        List<Long> operatorIds = getPeopleIds(selectStandard, ids_s, companyId);
        return operatorIds;
    }



    /**
     * 获取可编辑字段
     *
     * @param flowId
     * @return
     */
    private List<String> getEnableFieldList(Long flowId) {
        HighFlow highFlow = highFlowService.getById(flowId);
        String enableFieldStr = highFlow.getEnableField();
        List<String> enableFields = new LinkedList<>();
        for (String enableField : enableFieldStr.split(",")) {
            enableFields.add(enableField);
        }
        return enableFields;
    }

    /**
     * 根据筛选条件获取对应流程的可编辑人员列表
     *
     * @param selectStandard
     * @param ids_s
     * @param companyId
     * @return
     */
    List<Long> getPeopleIds(Integer selectStandard, String ids_s, Long companyId) {
        String[] ids = ids_s.split(",");
        Map<String, Boolean> isIdExist = new HashMap<>();
        for (String id : ids) {
            isIdExist.put(id, Boolean.TRUE);
        }
        //
        LambdaQueryWrapper<SysUser> query = Wrappers.<SysUser>lambdaQuery();
        query.eq(SysUser::getCompanyid, companyId);
        List<SysUser> sysUsers = sysUserMapper.selectList(query);

        List<Long> user_ids = new LinkedList<>();

        // 根据职位选择
        if (selectStandard == 0) {
            sysUsers.forEach(user -> {
                String[] jobIds = user.getJobids().split(",");
                for (String jobId : jobIds) {
                    if (isIdExist.get(jobId) != null) {
                        user_ids.add(user.getId());
                        break;
                    }
                }
            });
        }

        // 根据角色选择
        else if (selectStandard == 1) {
            sysUsers.forEach(user -> {
                String[] roleIds = user.getRoleids().split(",");
                for (String roleId : roleIds) {
                    if (isIdExist.get(roleId) != null) {
                        user_ids.add(user.getId());
                        break;
                    }
                }
            });
        }

        // 根据岗位选择
        else if (selectStandard == 2) {
            sysUsers.forEach(user -> {
                String[] departIds = user.getDepartids().split(",");
                for (String departId : departIds) {
                    if (isIdExist.get(departId) != null) {
                        user_ids.add(user.getId());
                        break;
                    }
                }
            });

        }

        // 根据组织机构选择
        else if (selectStandard == 3) {
            sysUsers.forEach(user -> {
                String[] orgIds = user.getOrgids().split(",");
                for (String orgId : orgIds) {
                    if (isIdExist.get(orgId) != null) {
                        user_ids.add(user.getId());
                        break;
                    }
                }
            });
        }

        // 根据人员id选择
        else if (selectStandard == 4) {
            sysUsers.forEach(user -> {
                Long userId = user.getId();
                if (isIdExist.get(userId) != null) {
                    user_ids.add(user.getId());
                }
            });
        }

        return user_ids;
    }

    public Integer getFinishSubId(Integer currentStep, HighTicket highTicket) {
        Integer substep = 0;
        if (currentStep == 1) substep = 1;
        else if (currentStep == 2) {
            if (highTicket.getWorkerSign() != null) substep = 2;
            else if (highTicket.getSuperviseSign() != null) substep = 3;
        }
        else if (currentStep == 3) {
            if (highTicket.getDanger1() != null) substep = 4;
            else if (highTicket.getDanger2() != null) substep = 5;
        }
        else if (currentStep == 4) substep = 6;
        else if (currentStep == 5) {
            if (highTicket.getSceneLeadSign() != null) substep = 7;
            else if (highTicket.getPossessionSafeSign() != null) substep = 8;
            else if (highTicket.getCentralizeManageLeaderSign() != null) substep = 9;
        }
        else if (currentStep == 6) substep = 10;
        else if (currentStep == 7) substep = 11;
        else if (currentStep == 8) substep = 12;
        else if (currentStep == 9) substep = 13;
        else if (currentStep == 10) substep = 14;

        return substep;
    }


    public Integer updateCurrentStep(Integer currentStep, HighTicket newHighTicket) {
        Boolean isFinishCurrentStep = false;        // 假设大步骤未完成
        switch (currentStep) {
            case 1:
                if (newHighTicket.getIsCommit1() == 1) isFinishCurrentStep = true; break;
            case 2:
                if (newHighTicket.getIsCommit2() == 1 && newHighTicket.getIsCommit3() == 1) isFinishCurrentStep = true; break;
            case 3:
                if (newHighTicket.getIsCommit4() == 1 && newHighTicket.getIsCommit5() == 1) isFinishCurrentStep = true; break;
            case 4:
                if (newHighTicket.getIsCommit6() == 1) isFinishCurrentStep = true; break;
            case 5:
                if (newHighTicket.getIsCommit7() == 1 || newHighTicket.getIsCommit8() == 1 || newHighTicket.getIsCommit9() == 1) isFinishCurrentStep = true; break;
            case 6:
                if (newHighTicket.getIsCommit11() == 1) isFinishCurrentStep = true; break;
            case 7:
                if (newHighTicket.getIsCommit12() == 1) isFinishCurrentStep = true; break;
            case 8:
                if (newHighTicket.getIsCommit13() == 1) isFinishCurrentStep = true; break;
            case 9:
                if (newHighTicket.getIsCommit14() == 1) isFinishCurrentStep = true; break;
        }
        return isFinishCurrentStep == true ? ++currentStep : currentStep;
    }
}
